package com.joysuch.wwyt.app.controller;


import com.joysuch.wwyt.app.bean.AppPendingTaskDto;
import com.joysuch.wwyt.app.service.AppCommonService;
import com.joysuch.wwyt.bp.bean.AppPendingTaskBean;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.websocket.MonitorPointDataWebSocket;
import com.joysuch.wwyt.workflow.entity.WorkFlowOption;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/bp/app")
@Api(tags = "/bp/app --App 公共接口")
@CrossOrigin
public class AppCommonController {

    @Autowired
    private AppCommonService appCommonService;
    @Value("${wwyt.file.upload.dir}")
    private String appDownloadDir;
    @Value("${wwyt.file.upload.dir}")
    private String apkUploadUrl;

/*    @GetMapping("/pendingTaskList")
    @ResponseBody
    @ApiOperation(value = "获取APP待办列表", response = WorkFlowOption.class)
    public ResultBean pendingTaskList() {
        List<AppPendingTaskBean> list = appCommonService.getPendingTaskList();
        return ResultBean.success(list);
    }*/

    @GetMapping("/v2/pendingTaskList")
    @ResponseBody
    @ApiOperation(value = "app待办事项列表", response = AppPendingTaskDto.class)
    public ResultBean v2PendingTaskList(Integer type) { // type: 1-流程审批 0-其他业务待办
        return appCommonService.v2PendingTaskList(type);
    }

    @GetMapping("/v2/appMenuList")
    @ResponseBody
    @ApiOperation(value = "app菜单列表")
    public ResultBean v2AppMenuList() {
        return appCommonService.v2AppMenuList();
    }

    @GetMapping("/v2/workSafety/getMenu")
    @ResponseBody
    @ApiOperation("app-作业票获取子菜单")
    public ResultBean v2WorkSafetyMenu(Long id) {
        return appCommonService.v2WorkSafetyMenu(id);
    }


    @GetMapping("/appMenuList")
    @ResponseBody
    @ApiOperation(value = "获取APP菜单列表")
    public ResultBean appMenuList() {
        List<String> list = new ArrayList<>();
        list.add("隐患整改");
        list.add("整改验收");
        return ResultBean.success(list);
    }

    @GetMapping("/v3/appMenuList")
    @ResponseBody
    @ApiOperation(value = "app菜单列表-v3")
    public ResultBean v3AppMenuList() {
        return ResultBean.success(appCommonService.v3AppMenuList());
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载app")
    public void download(HttpServletResponse response) {
        response.setHeader("Content-Disposition", "attachment;fileName=" + "wwytapp.apk");
        response.setContentType("application/vnd.android.package-archive");
        try (FileInputStream fileInputStream = new FileInputStream(appDownloadDir + "/app/wwytapp.apk");
             ServletOutputStream outputStream = response.getOutputStream()) {
            response.setContentLength(fileInputStream.available());
            byte[] data = new byte[1024 * 6];
            int len = -1;
            while ((len = fileInputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
        } catch (Exception e) {
            log.error("app下载失败", e);
        }
    }

    /**
     * app上传
     */
    @PostMapping("/appUpload")
    @ResponseBody
    @ApiOperation(value = "上传app")
    @RequiresPermissions("bp:app:appUpload")
    public Object uploadApp(MultipartHttpServletRequest request) {
        try {
            Map<String, MultipartFile> fileMap = request.getFileMap();
            if (fileMap.size() > 10) {
                Assert.state(false, "一次最多上传10个文件");
            }
            List<BaseAttachmentBean> attachments = new ArrayList<>(fileMap.size());
            for (Map.Entry<String, MultipartFile> e : fileMap.entrySet()) {
                MultipartFile cover1 = e.getValue();
                String fileName = "wwytapp";
                String extension = FilenameUtils.getExtension(cover1.getOriginalFilename());
                //文件夹
                String dir = apkUploadUrl + File.separator + "app";
                //String relativePath ="app" + "/" + fileName + "." + extension;
                File newFile = new File(dir + File.separator + fileName + "." + extension);
                FileUtils.forceMkdir(new File(dir));
                cover1.transferTo(newFile);
                BaseAttachmentBean bean = new BaseAttachmentBean();
                bean.setDownloadUrl(dir + File.separator + fileName + "." + extension);
                bean.setName(fileName + extension);
                attachments.add(bean);
            }
            return ResultBean.success(attachments);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBean.fail(107, "app上传失败");
    }

    @GetMapping("announce-show")
    @ResponseBody
    @ApiOperation("app 首页显示公告信息")
    public ResultBean announceShow() {
        if (Context.getCurrentTenantId() == null || StringUtils.isBlank(Context.getCompanyCode())) {
            return ResultBean.fail(101, "系统异常");
        }
        return ResultBean.success(MonitorPointDataWebSocket.getScreenMap().get(Context.getCurrentTenantId() + "_" + Context.getCompanyCode().substring(0, 7)));
    }

}
